package account

import (
	"gitee.com/xinshortlink/internal/dto"
	"gitee.com/xinshortlink/internal/dto/resp"
	"gitee.com/xinshortlink/internal/service/account"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type Api struct {
	service *account.Service
	logger  *zap.Logger
	resp    *resp.Util
}

func NewApi(service *account.Service, logger *zap.Logger, resp *resp.Util) *Api {
	return &Api{service: service, logger: logger, resp: resp}
}

// Login 登录
func (api *Api) Login(ctx *gin.Context) {
	var req = &dto.LoginReq{}
	if err := ctx.ShouldBindJSON(req); err != nil {
		api.resp.Resp(ctx, err, nil)
		return
	}

	accessToken, err := api.service.Login(ctx.Request.Context(), req.AccountName, req.Password, req.Captcha, req.Remember)
	api.resp.Resp(ctx, err, accessToken)
}

// Logout 登出
func (api *Api) Logout(ctx *gin.Context) {
	err := api.service.Logout(ctx)
	api.resp.Resp(ctx, err, nil)
}

// Register 注册账号
func (api *Api) Register(ctx *gin.Context) {
	var req = &dto.RegisterReq{}
	if err := ctx.ShouldBindJSON(req); err != nil {
		api.resp.Resp(ctx, err, nil)
		return
	}

	err := api.service.CreateAccount(ctx.Request.Context(), &dto.AccountDTO{
		AccountName: req.AccountName,
		Nickname:    req.Nickname,
		Password:    req.Password,
		Phone:       req.Phone,
		Email:       req.Email,
	})

	api.resp.Resp(ctx, err, nil)
}

// UpdateAccount 更新账户信息
func (api *Api) UpdateAccount(ctx *gin.Context) {
	var req = &dto.UpdateAccountReq{}
	if err := ctx.ShouldBindJSON(req); err != nil {
		api.resp.Resp(ctx, err, nil)
		return
	}

	err := api.service.UpdateAccount(ctx.Request.Context(), &dto.AccountDTO{
		Nickname: req.Nickname,
		Phone:    req.Phone,
		Email:    req.Email,
	})
	api.resp.Resp(ctx, err, nil)
}

// CurrentAccount 当前登录人信息
func (api *Api) CurrentAccount(ctx *gin.Context) {
	temp, err := api.service.CurrentAccount(ctx.Request.Context())
	api.resp.Resp(ctx, err, temp)
}

// HasAccount 账户是否存在
func (api *Api) HasAccount(ctx *gin.Context) {
	var req = &dto.HasAccountReq{}
	if err := ctx.ShouldBindQuery(req); err != nil {
		api.resp.Resp(ctx, err, nil)
		return
	}

	has, err := api.service.HasAccount(ctx.Request.Context(), req.AccountName)

	api.resp.Resp(ctx, err, has)
}
